package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"fmt"

	"github.com/globalsign/mgo/bson"
)

// 分享码
func GetShareCode(us *m.User) (code string, err error) {
	shareGame := us.GetShareGame()
	if shareGame.ShareCode != "" {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("该玩家已经分享过了 %s", shareGame.ShareCode))
		return
	}
	shareGame.ShareCode = us.IdentifId
	shareGame.Update(shareGame)
	code = shareGame.ShareCode
	return
}

// 获取分享码的道具
func GetShareCodeProp(from string, us *m.User, shareCode string, PSend func(interface{}) error) (uProp *m.UpdateProp, resGoods []*m.Goods, boxResList []*m.BoxRes, tuUid string, mail *m.Mail, err error) {
	tuShareGame, err := m.FindShareGameByShareCode(shareCode)
	if err != nil {
		return
	}
	uid := us.Uid.Hex()
	// 该玩家已经领取过
	if _, ok := tuShareGame.FriendUid[uid]; ok {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("该玩家已经领取过分享码"))
		return
	}
	tuUid = tuShareGame.Uid.Hex()

	shareGame := us.GetShareGame()
	if shareGame.FriendCode != "" {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("该玩家不是新手，已经领过奖励"))
		return
	}

	tpl, ok := data.Get("ShareGames", uint64(1))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到ShareGames配表，或者没有索引1的数据"))
		return
	}
	tplT := tpl.(data.ShareGame)
	giveGoods := make([]m.BaseKV, 0)
	for _, item := range tplT.ExchangeRewards {
		giveGoods = append(giveGoods, m.BaseKV{
			Key: int64(item.Key),
			Val: int64(item.Value),
		})
	}
	uProp, resGoods, boxResList, err = GiveGoodsByKvList(from, us, giveGoods, PSend)
	if err != nil {
		return
	}
	// 记录领过的玩家
	tuShareGame.FriendUid[uid] = uid
	tuShareGame.Update(tuShareGame)
	// 记录玩家领过的分享码
	shareGame.FriendCode = shareCode
	shareGame.Update(shareGame)

	mailRes := make([]*m.Goods, 0)
	for _, item := range tplT.ShareRewards {
		mailRes = append(mailRes, &m.Goods{
			Tid: int64(item.Key),
			Num: int64(item.Value),
		})
	}
	mail = &m.Mail{
		Id:      bson.NewObjectId(),
		Title:   tplT.Title,
		Content: tplT.Content,
		Res:     mailRes,
		Time:    utils.TNow().Unix(),
	}
	tuUser := GetUser(tuUid)
	// 给分享游戏的玩家添加邮件
	tuUser.GetUserMail().AddMail(mail)
	return
}
